<template>
  <div class="zone-management-page">
    <!-- 加载遮罩 -->
    <div v-if="zoneManagementStore.loadingState.isLoading" class="loading-overlay">
      <div class="loading-container">
        <el-progress 
          :percentage="zoneManagementStore.loadingState.progress" 
          :stroke-width="8"
          :show-text="false"
          class="loading-progress"
        />
        <div class="loading-message">{{ zoneManagementStore.loadingState.message }}</div>
        <div class="loading-stage">{{ getStageText(zoneManagementStore.loadingState.stage) }}</div>
      </div>
    </div>

    <!-- 欢迎提示 -->
    <el-alert
      v-if="zoneManagementStore.showWelcomeMessage"
      title="欢迎使用分区管理功能"
      type="info"
      :closable="false"
      show-icon
      class="welcome-alert"
    >
      <template #default>
        <p>这是您第一次进入该社区的分区管理页面，您可以：</p>
        <ul>
          <li>从左侧楼栋库拖拽楼栋到画布</li>
          <li>创建分区并设置分区边界</li>
          <li>调整楼栋位置和分区布局</li>
          <li>点击保存按钮保存您的设置</li>
        </ul>
      </template>
    </el-alert>
    
    <!-- 数据恢复提示 -->
    <el-alert
      v-if="zoneManagementStore.showDataRecoveryMessage"
      title="发现已有分区数据"
      type="success"
      :closable="false"
      show-icon
      class="recovery-alert"
    >
      <template #default>
        <p>检测到该社区已有 {{ zoneManagementStore.communityEntryState.zoneCount }} 个分区，正在加载...</p>
        <p v-if="zoneManagementStore.communityEntryState.lastModifiedTime">
          最后修改时间：{{ formatDateTime(zoneManagementStore.communityEntryState.lastModifiedTime) }}
        </p>
      </template>
    </el-alert>
    
    <!-- 操作模式指示器 -->
    <div class="operation-mode-indicator">
      <el-tag :type="zoneManagementStore.getOperationMode === 'CREATE' ? 'primary' : 'success'">
        {{ zoneManagementStore.getOperationMode === 'CREATE' ? '创建模式' : '编辑模式' }}
      </el-tag>
    </div>

    <!-- 社区信息栏 -->
    <div v-if="zoneManagementStore.communityInfo" class="community-info-bar">
      <el-card shadow="never" class="community-card">
        <div class="community-info">
          <div class="community-name">
            <el-icon><House /></el-icon>
            <span>{{ zoneManagementStore.communityInfo.communityName }}</span>
          </div>
          <div class="community-address">
            <el-icon><Location /></el-icon>
            <span>{{ zoneManagementStore.communityInfo.communityAddress }}</span>
          </div>
          <div class="community-stats">
            <el-tag type="info" size="small">
              楼栋: {{ zoneManagementStore.buildingList.length }}
            </el-tag>
            <el-tag type="success" size="small">
              分区: {{ zoneManagementStore.zoneList.length }}
            </el-tag>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <el-row :gutter="16" class="content-row">
        <!-- 左侧楼栋库 -->
        <el-col :span="6" class="building-library">
          <el-card shadow="never" class="building-card">
            <template #header>
              <div class="card-header">
                <span>楼栋库</span>
                <el-tag type="info" size="small">
                  {{ zoneManagementStore.availableBuildings.length }} 个可用
                </el-tag>
              </div>
            </template>
            
            <div class="building-list">
              <div
                v-for="building in zoneManagementStore.availableBuildings"
                :key="building.id"
                class="building-item"
                draggable="true"
                @dragstart="handleBuildingDragStart($event, building)"
              >
                <el-icon><OfficeBuilding /></el-icon>
                <span class="building-name">{{ building.buildingName }}</span>
                <span class="building-type">{{ building.buildingTypeName || '住宅楼' }}</span>
              </div>
              
              <div v-if="zoneManagementStore.availableBuildings.length === 0" class="empty-state">
                <el-empty description="暂无可用楼栋" :image-size="60" />
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 中间画布区域 -->
        <el-col :span="12" class="canvas-area">
          <el-card shadow="never" class="canvas-card">
            <template #header>
              <div class="card-header">
                <span>分区画布</span>
                <div class="canvas-tools">
                  <el-button-group>
                    <el-button size="small" type="primary" @click="handleSelectMode">
                      <el-icon><Pointer /></el-icon>
                      选择
                    </el-button>
                    <el-button size="small" @click="handleCreateZone">
                      <el-icon><Plus /></el-icon>
                      创建分区
                    </el-button>
                  </el-button-group>
                </div>
              </div>
            </template>
            
            <div class="canvas-container" ref="canvasContainer">
              <canvas
                ref="canvas"
                class="zone-canvas"
                @drop="handleCanvasDrop"
                @dragover="handleCanvasDragOver"
                @click="handleCanvasClick"
              ></canvas>
              
              <!-- 操作提示 -->
              <div class="operation-tips">
                <p>💡 操作提示：</p>
                <ul>
                  <li>从左侧拖拽楼栋到画布</li>
                  <li>点击创建分区按钮生成新分区</li>
                  <li>拖拽分区边框调整形状</li>
                  <li>右键删除楼栋</li>
                  <li>按Delete键删除选中楼栋</li>
                </ul>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 右侧分区列表 -->
        <el-col :span="6" class="zone-list">
          <el-card shadow="never" class="zone-card">
            <template #header>
              <div class="card-header">
                <span>分区列表</span>
                <el-button size="small" type="success" @click="handleSave">
                  <el-icon><Check /></el-icon>
                  保存
                </el-button>
              </div>
            </template>
            
            <div class="zone-list-content">
              <div
                v-for="zone in zoneManagementStore.zoneList"
                :key="zone.id"
                class="zone-item"
                :class="{ 'zone-selected': selectedZoneId === zone.id }"
                @click="handleZoneSelect(zone)"
              >
                <div class="zone-info">
                  <div class="zone-name">{{ zone.zoneName }}</div>
                  <div class="zone-code">{{ zone.zoneCode }}</div>
                  <div class="zone-type">{{ zone.zoneType }}</div>
                </div>
                <div class="zone-actions">
                  <el-button size="small" type="primary" @click.stop="handleEditZone(zone)">
                    编辑
                  </el-button>
                  <el-button size="small" type="danger" @click.stop="handleDeleteZone(zone)">
                    删除
                  </el-button>
                </div>
              </div>
              
              <div v-if="zoneManagementStore.zoneList.length === 0" class="empty-state">
                <el-empty description="暂无分区" :image-size="60" />
                <el-button type="primary" @click="handleCreateZone">创建第一个分区</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { House, Location, OfficeBuilding, Pointer, Plus, Check } from '@element-plus/icons-vue'
import { useZoneManagementStore } from '@/store/zoneManagement'
import { Building, Zone } from '@/types/zone'

// 组件引用
const route = useRoute()
const canvasContainer = ref<HTMLDivElement>()
const canvas = ref<HTMLCanvasElement>()

// 状态管理
const zoneManagementStore = useZoneManagementStore()
const selectedZoneId = ref<number | null>(null)

// 页面初始化
onMounted(async () => {
  const communityId = Number(route.query.communityId)
  if (communityId) {
    try {
      // 判断进入状态
      await zoneManagementStore.determineEntryState(communityId)
      
      // 根据状态显示不同提示
      if (zoneManagementStore.showWelcomeMessage) {
        ElMessage.success('欢迎使用分区管理功能！')
      } else if (zoneManagementStore.showDataRecoveryMessage) {
        ElMessage.info(`正在加载 ${zoneManagementStore.communityEntryState.zoneCount} 个分区数据...`)
      }
      
      // 加载数据
      await zoneManagementStore.loadInitialData(communityId)
      
      // 初始化画布
      await nextTick()
      initCanvas()
      
    } catch (error) {
      console.error('页面初始化失败:', error)
      ElMessage.error('页面初始化失败，请刷新重试')
    }
  } else {
    ElMessage.error('缺少社区ID参数')
  }
})

// 初始化画布
const initCanvas = () => {
  if (!canvas.value || !canvasContainer.value) return
  
  const container = canvasContainer.value
  const ctx = canvas.value.getContext('2d')
  
  if (!ctx) return
  
  // 设置画布尺寸
  canvas.value.width = container.clientWidth
  canvas.value.height = container.clientHeight
  
  // 绘制网格背景
  drawGrid(ctx, canvas.value.width, canvas.value.height)
  
  // 如果有绘图数据，绘制分区和楼栋
  if (zoneManagementStore.drawingData) {
    drawZonesAndBuildings(ctx)
  }
}

// 绘制网格
const drawGrid = (ctx: CanvasRenderingContext2D, width: number, height: number) => {
  ctx.strokeStyle = '#f0f0f0'
  ctx.lineWidth = 1
  
  // 绘制垂直线
  for (let x = 0; x <= width; x += 20) {
    ctx.beginPath()
    ctx.moveTo(x, 0)
    ctx.lineTo(x, height)
    ctx.stroke()
  }
  
  // 绘制水平线
  for (let y = 0; y <= height; y += 20) {
    ctx.beginPath()
    ctx.moveTo(0, y)
    ctx.lineTo(width, y)
    ctx.stroke()
  }
}

// 绘制分区和楼栋
const drawZonesAndBuildings = (ctx: CanvasRenderingContext2D) => {
  // 这里实现分区和楼栋的绘制逻辑
  // 具体实现将在后续步骤中完成
}

// 获取阶段文本
const getStageText = (stage: string) => {
  const stageMap: Record<string, string> = {
    init: '初始化',
    community: '加载社区信息',
    buildings: '加载楼栋数据',
    zones: '加载分区信息',
    drawing: '加载绘图数据',
    complete: '完成'
  }
  return stageMap[stage] || stage
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 楼栋拖拽开始
const handleBuildingDragStart = (event: DragEvent, building: Building) => {
  if (event.dataTransfer) {
    event.dataTransfer.setData('application/json', JSON.stringify(building))
    event.dataTransfer.effectAllowed = 'copy'
  }
}

// 画布拖拽悬停
const handleCanvasDragOver = (event: DragEvent) => {
  event.preventDefault()
  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = 'copy'
  }
}

// 画布拖拽放置
const handleCanvasDrop = (event: DragEvent) => {
  event.preventDefault()
  
  if (!event.dataTransfer) return
  
  try {
    const buildingData = JSON.parse(event.dataTransfer.getData('application/json'))
    const rect = canvas.value?.getBoundingClientRect()
    
    if (rect) {
      const x = event.clientX - rect.left
      const y = event.clientY - rect.top
      
      // 处理楼栋放置逻辑
      handleBuildingDrop(buildingData, x, y)
    }
  } catch (error) {
    console.error('处理楼栋放置失败:', error)
  }
}

// 处理楼栋放置
const handleBuildingDrop = (building: Building, x: number, y: number) => {
  // 这里实现楼栋放置逻辑
  // 具体实现将在后续步骤中完成
  console.log('楼栋放置:', building, x, y)
}

// 画布点击
const handleCanvasClick = (event: MouseEvent) => {
  // 这里实现画布点击逻辑
  // 具体实现将在后续步骤中完成
}

// 选择模式
const handleSelectMode = () => {
  // 这里实现选择模式逻辑
  // 具体实现将在后续步骤中完成
}

// 创建分区
const handleCreateZone = () => {
  // 这里实现创建分区逻辑
  // 具体实现将在后续步骤中完成
  ElMessage.info('创建分区功能将在后续实现')
}

// 分区选择
const handleZoneSelect = (zone: Zone) => {
  selectedZoneId.value = zone.id || null
  // 这里实现分区选择逻辑
  // 具体实现将在后续步骤中完成
}

// 编辑分区
const handleEditZone = (zone: Zone) => {
  // 这里实现编辑分区逻辑
  // 具体实现将在后续步骤中完成
  ElMessage.info('编辑分区功能将在后续实现')
}

// 删除分区
const handleDeleteZone = async (zone: Zone) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分区"${zone.zoneName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里实现删除分区逻辑
    // 具体实现将在后续步骤中完成
    ElMessage.success('删除分区功能将在后续实现')
  } catch {
    // 用户取消删除
  }
}

// 保存数据
const handleSave = async () => {
  try {
    // 这里实现保存数据逻辑
    // 具体实现将在后续步骤中完成
    ElMessage.info('保存功能将在后续实现')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请重试')
  }
}
</script>

<style scoped>
.zone-management-page {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 120px);
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-container {
  background: white;
  padding: 40px;
  border-radius: 8px;
  text-align: center;
  min-width: 300px;
}

.loading-progress {
  margin-bottom: 20px;
}

.loading-message {
  font-size: 16px;
  color: #333;
  margin-bottom: 10px;
}

.loading-stage {
  font-size: 14px;
  color: #666;
}

.welcome-alert,
.recovery-alert {
  margin-bottom: 20px;
}

.operation-mode-indicator {
  margin-bottom: 20px;
  text-align: center;
}

.community-info-bar {
  margin-bottom: 20px;
}

.community-card {
  border: none;
}

.community-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.community-name,
.community-address {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #333;
}

.community-stats {
  display: flex;
  gap: 10px;
}

.content-row {
  height: calc(100vh - 300px);
}

.building-library,
.canvas-area,
.zone-list {
  height: 100%;
}

.building-card,
.canvas-card,
.zone-card {
  height: 100%;
  border: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.building-list {
  height: calc(100% - 60px);
  overflow-y: auto;
}

.building-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px;
  margin-bottom: 8px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  cursor: grab;
  transition: all 0.3s;
}

.building-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.building-item:active {
  cursor: grabbing;
}

.building-name {
  font-weight: 500;
  color: #333;
}

.building-type {
  font-size: 12px;
  color: #666;
  margin-left: auto;
}

.canvas-container {
  position: relative;
  height: calc(100% - 60px);
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  overflow: hidden;
}

.zone-canvas {
  width: 100%;
  height: 100%;
  cursor: crosshair;
}

.operation-tips {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(255, 255, 255, 0.9);
  padding: 15px;
  border-radius: 6px;
  font-size: 12px;
  color: #666;
  max-width: 200px;
}

.operation-tips ul {
  margin: 5px 0 0 0;
  padding-left: 15px;
}

.operation-tips li {
  margin-bottom: 3px;
}

.zone-list-content {
  height: calc(100% - 60px);
  overflow-y: auto;
}

.zone-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  margin-bottom: 10px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.zone-item:hover {
  background: #e9ecef;
}

.zone-item.zone-selected {
  background: #e6f7ff;
  border-color: #1890ff;
}

.zone-info {
  flex: 1;
}

.zone-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
}

.zone-code {
  font-size: 12px;
  color: #666;
  margin-bottom: 3px;
}

.zone-type {
  font-size: 12px;
  color: #999;
}

.zone-actions {
  display: flex;
  gap: 5px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.canvas-tools {
  display: flex;
  gap: 10px;
}
</style>
